<template>
  <div class="app-container">
    <!-- 条件搜索 -->
    <div class="filter-container">
      <el-form ref="queryForm" :model="listQuery.param" size="small" :inline="true" label-width="auto">
        <el-form-item label="所属应用" prop="appName">
          <el-input v-model="listQuery.param.appName" placeholder="所属应用" class="filter-item" @keyup.enter.native="handleFilterQuery" />
        </el-form-item>
        <el-form-item label="客户端ID" prop="clientId">
          <el-input v-model="listQuery.param.clientId" placeholder="客户端ID" style="width: 280px;" class="filter-item" @keyup.enter.native="handleFilterQuery" />
        </el-form-item>
        <el-form-item label="使用状态" prop="status">
          <el-select v-model="listQuery.param.status" placeholder="使用状态" style="width: 150px;" class="filter-item" @change="handleFilterQuery">
            <el-option v-for="item in statusOptions" :key="item.code" :label="item.text" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" style="margin-left: 10px;" @click="handleFilterQuery">
          搜索
        </el-button>
        <el-button v-waves class="filter-item" icon="el-icon-refresh-right" @click="handleRestQuery">
          重置
        </el-button>
      </el-form>
    </div>
    <div class="filter-container">
      <div style="float: left;">
        <el-button v-permission="permission.add" class="filter-item" type="primary" plain icon="el-icon-plus" @click="handleCreate">
          新增
        </el-button>
      </div>
      <div style="float: right;">
        <el-button icon="el-icon-refresh" circle @click="handleFilterQuery" />
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table
      :key="tableKey"
      v-loading="loading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      scrollbar-always-on="true"
    >
      <el-table-column type="selection" width="50px" align="center" />
      <el-table-column label="序号" type="index" width="50px" align="center" />
      <el-table-column label="客户端KEY" min-width="140px" align="left">
        <template v-slot="{row}">
          <span>{{ row.appSecret }}</span>
        </template>
      </el-table-column>
      <el-table-column label="客户端ID" min-width="140px" align="left">
        <template v-slot="{row}">
          <span>{{ row.clientId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属应用" min-width="100px" align="left">
        <template v-slot="{row}">
          <span>{{ row.appName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="权限范围" min-width="80px" align="left">
        <template v-slot="{row}">
          <el-tag v-if="row.scope === 'all'" type="success">全部</el-tag>
          <el-tag v-else type="success">未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="授权类型" min-width="200px" align="left">
        <template v-slot="{row}">
          <el-tag v-for="(item, index) in row.authorizedGrantTypes.split(',')" :key="index" v-text="getGrantType(item)" />
        </template>
      </el-table-column>
      <el-table-column label="重定向URI" min-width="120px" align="left" :show-overflow-tooltip="true">
        <template v-slot="{row}">
          <span>{{ row.webServerRedirectUri }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Token超时时间" min-width="105px" align="left">
        <template v-slot="{row}">
          <span>{{ row.accessTokenValidity }}s</span>
        </template>
      </el-table-column>
      <el-table-column label="Token刷新时间" min-width="105px" align="left">
        <template v-slot="{row}">
          <span>{{ row.refreshTokenValidity }}s</span>
        </template>
      </el-table-column>
      <el-table-column label="自动审核" min-width="80px" align="left">
        <template v-slot="{row}">
          <el-tag v-if="row.autoapprove === 'true'">是</el-tag>
          <el-tag v-else-if="row.autoapprove === 'false'">否</el-tag>
          <el-tag v-else>未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="使用状态" class-name="status-col" width="70px">
        <template v-slot="{row}">
          <el-switch :value="row.status ==='Y'" disabled />
        </template>
      </el-table-column>
      <el-table-column label="备注" min-width="80px" align="left">
        <template v-slot="{row}">
          <span>{{ row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新人" min-width="70px" align="left">
        <template v-slot="{row}">
          <span>{{ row.updatedBy }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" width="140px" align="left">
        <template v-slot="{row}">
          <span>{{ row.updatedTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="160px" class-name="small-padding fixed-width">
        <template v-slot="{row,$index}">
          <el-button size="mini" type="info" icon="el-icon-document" @click="handleDetail(row, $index)">详情</el-button>
          <el-dropdown style="margin-left: 10px;" @command="handleClick($event, row, $index)">
            <el-button size="mini" type="primary">更多
              <i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-dropdown-menu>
              <el-dropdown-item v-permission="permission.edit" command="edit"><i class="el-icon-edit"> 编辑</i></el-dropdown-item>
              <el-dropdown-item v-permission="permission.del" command="del"><i class="el-icon-delete"> 删除</i></el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 表格分页 -->
    <pagination :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="handleInit" />

    <!-- 编辑页面 -->
    <el-drawer
      :visible.sync="visible"
      direction="rtl"
      size="40%"
      :close-on-press-escape="false"
      :wrapper-closable="false"
      :show-close="false"
    >
      <template v-slot:title>
        <div class="drawer-header">
          <span>{{ title[state] }}</span>
          <div>
            <el-button icon="el-icon-close" @click="handleClose">
              取消
            </el-button>
            <el-button v-if="state !=='detail'" :loading="submitting" type="primary" icon="el-icon-check" @click="handleSubmitFormData">
              <span v-if="!submitting">确认</span>
              <span v-else>提 交 中...</span>
            </el-button>
          </div>
        </div>
      </template>
      <el-form ref="dataForm" :rules="rules" :model="formData" label-position="right" label-width="110px">
        <el-input v-model="formData.id" type="hidden" />
        <el-row>
          <el-col :span="24">
            <el-form-item label="客户端ID" prop="clientId">
              <el-input v-model="formData.clientId" readonly placeholder="系统自动生成" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="客户端KEY" prop="appSecret">
              <el-input v-model="formData.appSecret" readonly placeholder="系统自动生成" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="所属应用" prop="appName">
              <el-input v-model="formData.appName" :readonly="state==='detail'" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限范围" prop="scope">
              <el-select v-model="formData.scope" :disabled="state==='detail'" style="width: 100%;" placeholder="请选择 clearable">
                <el-option key="all" label="全部" value="all" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="授权类型" prop="authorizedGrantTypes">
              <el-select v-model="formData.authorizedGrantTypes" :disabled="state==='detail'" multiple style="width: 100%;" placeholder="请选择">
                <el-option
                  v-for="item in grantTypes"
                  :key="item.code"
                  :label="item.text"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="重定向URI" prop="webServerRedirectUri">
              <el-input v-model="formData.webServerRedirectUri" :readonly="state==='detail'" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="访问令牌效期" prop="accessTokenValidity">
              <el-input v-model="formData.accessTokenValidity" :readonly="state==='detail'" placeholder="请输入" clearable>
                <template v-slot:append>s</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="更新令牌效期" prop="refreshTokenValidity">
              <el-input v-model="formData.refreshTokenValidity" :readonly="state==='detail'" placeholder="请输入" clearable>
                <template v-slot:append>s</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="扩展信息" prop="additionalInformation">
              <el-input v-model="formData.additionalInformation" :readonly="state==='detail'" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="自动审核" prop="autoapprove">
              <el-select v-model="formData.autoapprove" :disabled="state==='detail'" style="width: 100%;" placeholder="请选择 clearable">
                <el-option key="true" label="是" value="true" />
                <el-option key="false" label="否" value="false" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="使用状态" prop="status">
              <el-radio v-model="formData.status" :disabled="state==='detail'" label="Y">启用</el-radio>
              <el-radio v-model="formData.status" :disabled="state==='detail'" label="N">禁用</el-radio>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="formData.remark" :readonly="state==='detail'" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-close" @click="handleClose">
          取消
        </el-button>
        <el-button v-if="state !=='detail'" :loading="submitting" type="primary" icon="el-icon-check" @click="handleSubmitFormData">
          <span v-if="!submitting">确认</span>
          <span v-else>提 交 中...</span>
        </el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { getPageList, handleSave, handleDelete } from './api'
import permission from '@/directive/permission/index' // 权限判断指令
// import checkPermission from '@/utils/permission' // 权限判断函数
import waves from '@/directive/waves' // waves directive
// import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'

export default {
  // 当前页面名称（组件）
  name: 'PostInfo',
  // 引用组件
  components: { Pagination },
  directives: { permission, waves },
  filters: {},
  data() {
    return {
      // 列表table的key
      tableKey: 0,
      // 遮罩层
      loading: true,
      // table数据对象
      list: [],
      // 总条数
      total: 0,
      // table条件查询对象
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        // sort: '+id',
        param: {
          appName: undefined,
          clientId: undefined,
          status: undefined
        }
      },
      // 状态字典
      statusOptions: [{ code: 'Y', text: '启用' }, { code: 'N', text: '禁用' }],
      // 授权类型
      grantTypes: [{ code: 'authorization_code', text: '授权码' }, { code: 'password', text: '密码' },
        { code: 'refresh_token', text: '刷新令牌' }, { code: 'sms_code', text: '短信验证' }, { code: 'implicit', text: '简化' }, { code: 'client_credentials', text: '客户端' }],
      // 表单数据对象
      formData: {},
      // 是否显示弹出层
      visible: false,
      // 弹出层状态值（新增和修改共用同一个表单页面）
      state: '',
      // 弹出层标题
      title: {
        update: '修改',
        create: '新增',
        detail: '详情'
      },
      // 权限标识
      permission: {
        add: ['sys:client:add'],
        edit: ['sys:client:edit'],
        del: ['sys:client:del']
      },
      submitting: false,
      // 表单校验规则
      rules: {
        appName: [{ required: true, message: '所属应用不能为空', trigger: 'change' }],
        scope: [{ required: true, message: '授权范围不能为空', trigger: 'change' }],
        authorizedGrantTypes: [{ required: true, message: '授权类型不能为空', trigger: 'change' }],
        accessTokenValidity: [{ required: true, message: '访问令牌超时时间不能为空', trigger: 'change' }],
        refreshTokenValidity: [{ required: true, message: '刷新令牌不能为空', trigger: 'change' }],
        autoapprove: [{ required: true, message: '是否自动审核不能为空', trigger: 'change' }]
      }
    }
  },
  computed: {},
  watch: {},
  created() {
    this.handleInit()
    this.handleRestFormData()
  },
  mounted() {},
  methods: {
    // 查询table数据对象
    handleInit() {
      this.loading = true
      getPageList(this.listQuery).then(res => {
        this.list = res.data
        if (res.total) {
          this.total = Number(res.total)
        }
        this.loading = false
      })
    },
    // 转换授权类型
    getGrantType(code) {
      // 使用计算属性来查找并返回text
      const item = this.grantTypes.find(grantType => grantType.code === code)
      return item ? item.text : '未知'
    },
    // 条件查询table数据
    handleFilterQuery() {
      this.listQuery.pageNum = 1
      this.handleInit()
    },
    // 重置table查询条件
    handleRestQuery() {
      this.$refs.queryForm.resetFields()
    },
    // 重置表单
    handleRestFormData() {
      this.formData = {
        id: undefined,
        appName: undefined,
        appSecret: undefined,
        clientId: undefined,
        scope: 'all',
        authorizedGrantTypes: undefined,
        webServerRedirectUri: undefined,
        accessTokenValidity: undefined,
        refreshTokenValidity: undefined,
        additionalInformation: undefined,
        autoapprove: 'true',
        status: 'Y',
        remark: ''
      }
    },
    // 更多点击操作项
    handleClick(item, row, index) {
      // 编辑
      if (item === 'edit') {
        this.handleUpdate(row, index)
      }
      // 删除
      if (item === 'del') {
        this.handleDelete(row, index)
      }
    },
    // 新增
    handleCreate() {
      this.state = 'create'
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 修改
    handleUpdate(row) {
      this.state = 'update'
      this.visible = true

      // 创建一个新的对象赋值
      this.formData = Object.assign({}, row)
      this.formData.authorizedGrantTypes = this.formData.authorizedGrantTypes.split(',')
      // 清理掉多余的属性值，避免数据不对问题
      delete this.formData.createdBy
      delete this.formData.createdTime
      delete this.formData.updatedBy
      delete this.formData.updatedTime
      delete this.formData.tenantId
      delete this.formData.revision
      delete this.formData.deleted

      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 详情
    handleDetail(row) {
      this.state = 'detail'
      this.visible = true

      // 创建一个新的对象赋值
      this.formData = Object.assign({}, row)
      this.formData.authorizedGrantTypes = this.formData.authorizedGrantTypes.split(',')

      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 删除
    handleDelete(row, index) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 显示加载遮罩
        const loading = this.$loading({ lock: true, text: '处理中...', body: true, fullscreen: false, background: 'rgba(0, 0, 0, 0.05)' })
        handleDelete({ postId: row.postId }).then((res) => {
          loading.close()
          //  刷新table
          this.handleFilterQuery()
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'success',
            duration: 4000
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 表单提交
    handleSubmitFormData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.submitting = true
          this.formData.authorizedGrantTypes = this.formData.authorizedGrantTypes.join(',')
          handleSave(this.formData).then((res) => {
            this.submitting = false
            //  刷新table
            this.handleFilterQuery()
            this.handleClose()
            this.$message({
              showClose: true,
              message: res.msg,
              type: 'success',
              duration: 4000
            })
          })
        }
      })
    },
    // 关闭弹出层
    handleClose() {
      this.$refs['dataForm'].resetFields()
      this.handleRestFormData()
      this.visible = false
    }
  }
}
</script>
<style>
.el-input.is-disabled .el-input__inner {
  background-color: #ffffff !important;
  cursor: pointer !important;
}
.el-radio.is-disabled .el-radio__inner {
  background-color: #ffffff !important;
  cursor: pointer !important;
}
.el-radio__input.is-disabled {
  background-color: #ffffff !important;
  cursor: pointer !important;
}
.el-radio__input.is-disabled.is-checked {
  background-color: #ffffff !important;
  cursor: pointer !important;
}
.el-radio__label {
  background-color: #ffffff !important;
  cursor: pointer !important;
}
.el-textarea.is-disabled .el-textarea__inner {
  background-color: #ffffff !important;
}
.vue-treeselect--disabled .vue-treeselect__control {
  background-color: #ffffff !important;
}
</style>
